package com.ml.rabbitmq.d_direct.old;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeoutException;

/**
 * @author xr-8
 * @create 2021-04-14 22:56
 */
public class Producer {

    public static void main(String[] args) {
        //1创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
//        connectionFactory.setVirtualHost("/ ");
        Connection connection = null;
        Channel channel = null;
        try {
            //2创建连接Connection
            connection = connectionFactory.newConnection("生产者");
            //3通过连接获取通道Channel
            channel = connection.createChannel();
            //4准备交换机
            String exchangeName = "direct_message_exchange";
            //5指定交换机类型
            String exchangeType = "direct";

            //6声明交换机 所谓的持久化是指 交换机不会随着服务的重启而丢失，true 不丢失 false 重启丢失
            channel.exchangeDeclare(exchangeName, exchangeType, true);
            //7声明队列
            channel.queueDeclare("queue5",true,false,false,null);
            channel.queueDeclare("queue6",true,false,false,null);
            channel.queueDeclare("queue7",true,false,false,null);
            //8绑定队列和交换机的关系
            channel.queueBind("queue5",exchangeName,"order");
            channel.queueBind("queue6",exchangeName,"order");
            channel.queueBind("queue7",exchangeName,"course");

            //9指定routing key
            String routingKey = "order";
            //10准备消息内容
            String message = "只要学不死，就往死里学";
            //11发送消息给中间件
            channel.basicPublish(exchangeName, routingKey, null, message.getBytes());
            System.out.println("消息发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //7关闭通道
            if (Objects.nonNull(channel) && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            //8关闭连接
            if (Objects.nonNull(connection) && connection.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
